<template>
	<view class="container" :style="{ paddingBottom: showMoreTool ? '220rpx' : '120rpx' }">
		<editor class="ql-container" :show-img-size="true" :show-img-toolbar="true" :show-img-resize="true" id="editor"
			@statuschange="statuschange" ref="editot" @input="getEditorContent" @ready="onEditorReady" v-html="this.draftContent"></editor>
		<!-- 操作工具 -->
		<view class="tool-view">
			<view class="tool">
				<jinicons class="single" type="&#xe6f3;" font-size="44rpx" title="插入图片" @click="insertImage"></jinicons>
				<jinicons class="single" type="&#xe6f9;" font-size="44rpx" title="修改文字样式" @click="showMore"
					:color="showMoreTool ? activeColor : '#666666'"></jinicons>
				<jinicons class="single" type="&#xe6eb;" font-size="44rpx" title="分割线" @click="insertDivider"></jinicons>
				<jinicons class="single" type="&#xe6e8;" font-size="44rpx" title="撤销" @click="undo()"></jinicons>
				<jinicons class="single" type="&#xe705;" font-size="44rpx" title="重做" @click="redo()"></jinicons>
				<jinicons class="single" type="&#xeb8a;" font-size="44rpx" title="发布" @click="showSetting"></jinicons>
			</view>
			<!-- 文字相关操作 -->
			<view class="font-more" :style="{ height: showMoreTool ? '100rpx' : 0 }">
				<jinicons class="single" style="z-index: 100;" type="&#xe6e7;" font-size="44rpx" title="加粗" @click="setBold"
					:color="showBold ? activeColor : '#666666'"></jinicons>
				<jinicons class="single" style="z-index: 100;" type="&#xe6fe;" font-size="44rpx" title="斜体" @click="setItalic"
					:color="showItalic ? activeColor : '#666666'"></jinicons>
				<jinicons class="single" style="z-index: 100;" type="&#xe6f8;" font-size="44rpx" title="分割线" @click="setIns"
					:color="showIns ? activeColor : '#666666'"></jinicons>
				<jinicons class="single" style="z-index: 100;" type="&#xe6e3;" font-size="44rpx" title="标题" @click="setHeader"
					:color="showHeader ? activeColor : '#666666'"></jinicons>
				<jinicons class="single" style="z-index: 100;" type="&#xe6f1;" font-size="44rpx" title="居中" @click="setCenter"
					:color="showCenter ? activeColor : '#666666'"></jinicons>
				<jinicons class="single" style="z-index: 100;" type="&#xe6ed;" font-size="44rpx" title="居右" @click="setRight"
					:color="showRight ? activeColor : '#666666'"></jinicons>
			</view>
			<view class="setting-layer" style="display: flex; flex-direction: row; z-index: 100;" v-if="showSettingLayer">
				<button class="btn btn-primary" @click="draft()" :disabled="isDisable">
					<jinicons class="icon" type="&#xe655;"></jinicons>
					<view>保存草稿</view>
				</button>
				<button class="btn btn-success" @click="contribute()" :disabled="isDisable">
					<jinicons class="icon" type="&#xe639;"></jinicons>
					<view>公开发布</view>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '../../util/api.js';
	import jinicons from './jin-icons.vue';
	import request from '../../util/request.js';
	export default {
		props: ['title', 'draftContent','username'],
		computed: {
			introductionList_: {
				get() {
					return this.introductionList
				},
				set(val) {
					// introductionList_改变由父组件控制
					this.$emit('on-change-introduction', val)
				}
			}
		},
		data() {
			return {
				isDisable: false,
				format: 'json',
				pageNo: 1,
				pageSize: 1,
				id: '',
				getimg: '',
				author: '',
				ImgUrl: '',
				session: '',
				SonContent: '',
				contentVal: '',
				contentText: '',
				showMoreTool: false,
				showBold: false,
				showItalic: false,
				showIns: false,
				showHeader: false,
				showCenter: false,
				showRight: false,
				showSettingLayer: false,
				activeColor: '#F56C6C',
				siteId: 'c859d5588b744fe28f83064b037d3890',
				ddraftContent: '',
				type:'video',
				thumb: 'thumb',
				uploadFile:'',
				//获取富文本内容
				tem:'',
				videourl:''
			};
		},
		components: {
			jinicons
		},
		mounted() {
			if (!this.editorCtx) {
				uni.createSelectorQuery().select('#editor').context((res) => {
					var contentVal_1 = this.draftContent;
					//将内容写入编辑器
					this.editorCtx = res.context;
					let EContent = {
						html: contentVal_1
					}
					this.editorCtx.setContents(EContent); //设置富文本编辑器的内容
				}).exec()
			}
		},
		methods: {
			contribute() {
				if(this.getimg == ''){
					uni.showToast({
						icon: 'none',
						title: '至少需要上传一张图片！'
					})
					return false;
				}
				if (this.tem == '' || this.title == '') {
					uni.showToast({
						title: '标题或内容不能为空。',
						icon: 'none'
					});
					return false;
				}
				var TitleData = {
					title: this.title,
					author: this.author,
					titleImg: this.getimg
				};
				var functionTitle = JSON.stringify(TitleData);
				this.SonContent = this.draftContent;
				request.postf(api.save, {
					session: this.session,
					info: functionTitle,
					txt: this.SonContent,
					titleImg: this.ImgUrl,
					username: this.username
				}).then(response => {
					if (response.data.code === 0) {
						uni.showToast({
							icon: 'none',
							title: '上传成功！',
						})
						this.time();
						this.getList();
					} else {
						uni.showToast({
							icon: 'none',
							title: '上传失败，请稍后重试！'
						})
					}
				}).catch(ex => {
					uni.showToast({
						icon: 'none',
						title: '上传失败，请稍后再试',
					})
				})
			},
			getEditorContent(e) { /////////////////////////获取编辑器内容，当前页面都能获取到
				var html = e.detail.html
				this.contentVal = e.detail.html;
				this.SonContent = this.contentVal;
				this.tem = this.SonContent
				this.contentText = e.detail.text;
				this.$emit('edit-content', this.contentVal);
			},
			time() {
				this.isDisable = true
				setTimeout(() => {
					this.isDisable = false
				}, 60000)
			},
			//投稿
			release() {
				request.put(api.sendToSite, {
					id: this.id,
					siteId: this.siteId,
					username: this.username
				}).then(response => {

				}).catch(ex => {
					uni.showToast({
						icon: 'none',
						title: '请求失败，请稍后再试'
					})
				})
			},
			//获取id
			getList() {
				let url = api.listDraft;
				url = url + "?format=" + this.format + "&pageNo=" + this.pageNo + "&pageSize=" + this.pageSize +
					"&session=&username=" + this.username;
				request.getf(url, {
					username: this.username
				}).then(response => {
					if (response.data.code === 0) {
						this.id = response.data.data.list[0].content.id;
						this.release();
					} else {
						uni.showToast({
							icon: 'none',
							title: '请求失败，' + response.data.msg,
						})
					}
				}).catch(ex => {
					console.log('ex=', ex);
					uni.showToast({
						icon: 'none',
						title: '请求失败，请稍后再试'
					})
				})
			},
			//保存草稿
			draft() {
				if(this.getimg == ''){
					uni.showToast({
						icon: 'none',
						title: '至少需要上传一张图片！'
					})
					return false;
				}
				if (this.tem == '' || this.title == '') {
					uni.showToast({
						title: '标题或内容不能为空。',
						icon: 'none'
					});
					return false;
				}
				var TitleData = {
					title: this.title,
					author: this.author,
					titleImg: this.getimg,
					video:this.videourl
				};
				var functionTitle = JSON.stringify(TitleData);
				this.ddraftContent = this.SonContent;
				request.postf(api.save, {
					session: this.session,
					info: functionTitle,
					txt: this.ddraftContent,
					titleImg: this.ImgUrl,
					username: this.username
				}).then(response => {
					if (response.data.code === 0) {
						uni.showToast({
							icon: 'none',
							title: '上传成功！',
						})
						this.time();
					} else {
						uni.showToast({
							icon: 'none',
							title: '上传失败，请稍后重试！'
						})
					}
				}).catch(ex => {
					uni.showToast({
						icon: 'none',
						title: '上传失败，请稍后再试',
					})
				})
			},		
			onEditorReady() {
				/////////////////////////初始化
				if (this.draftContent == '') {
					uni.createSelectorQuery().select('#editor').context((res) => {
						var contentVal_1 = this.contentVal;
						//将内容写入编辑器
						this.editorCtx = res.context;
						let EContent = {
							html: contentVal_1
						}
						this.editorCtx.setContents(EContent); //设置富文本编辑器的内容
					}).exec()
				}
			},
			undo() {
				this.editorCtx.undo();
			},
			// 插入图片
			insertImage() {
				uni.chooseImage({
					count: 1, //默认1
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: async (res) => {
						var tempFiles = res.tempFiles;
						uni.showLoading({
							title: '正在上传中...'
						})
						for (let temp of tempFiles) {
							uni.uploadFile({
								url: api.uploadAttachsUrl,
								formData: {
									Filedata: temp,
									siteId: this.siteId,
									type: this.thumb
								},
								success: res => {
									// 上传完成后处理
									var imgUrl = "http://res.sdast.org" + JSON.parse(res.data)
									.msg;
									this.$emit('ImgUrl', imgUrl);
									this.getimg = imgUrl;
									//在富文本初始化的时候创建一个名为editorCtx的上下文，并且调用了官网上的insertImage函数，用来获得地址和img标签
									this.editorCtx.insertImage({
										src: imgUrl, // 此处需要将图片地址切换成服务器返回的真实图片地址
										alt: '图片',
										success: function(e) {

										},
									});
									uni.hideLoading();
								},
							});
						}
					}
				});
			},
			insertDivider() {
				this.editorCtx.insertDivider();
			},
			redo() {
				this.editorCtx.redo();
			},
			showMore() {
				this.showMoreTool = !this.showMoreTool;
				this.editorCtx.setContents()
			},
			setBold() {
				this.showBold = !this.showBold;
				this.editorCtx.format('bold');
			},
			setItalic() {
				this.showItalic = !this.showItalic;
				this.editorCtx.format('italic');
			},
			checkStatus(name, detail, obj) {
				//hasOwnProperty()方法返回一个布尔值，判断对象是否包含特定的自身（非继承）属性。
				if (detail.hasOwnProperty(name)) {
					this[obj] = true;
				} else {
					this[obj] = false;
				}
			},
			statuschange(e) {
				var detail = e.detail;
				this.checkStatus('bold', detail, 'showBold');
				this.checkStatus('italic', detail, 'showItalic');
				this.checkStatus('ins', detail, 'showIns');
				this.checkStatus('header', detail, 'showHeader');
				if (detail.hasOwnProperty('align')) {
					if (detail.align == 'center') {
						this.showCenter = true;
						this.showRight = false;
					} else if (detail.align == 'right') {
						this.showCenter = false;
						this.showRight = true;
					} else {
						this.showCenter = false;
						this.showRight = false;
					}
				} else {
					this.showCenter = false;
					this.showRight = false;
				}
			},
			setIns() {
				this.showIns = !this.showIns;				
				this.editorCtx.format('ins');
			},
			setHeader() {
				this.showHeader = !this.showHeader;
				this.editorCtx.format('header', this.showHeader ? 'H2' : false);
			},
			setCenter() {
				this.showCenter = !this.showCenter;
				this.editorCtx.format('align', this.showCenter ? 'center' : false);
			},
			setRight() {
				this.showRight = !this.showRight;
				this.editorCtx.format('align', this.showRight ? 'right' : false);
			},
			showSetting() {
				this.showSettingLayer = !this.showSettingLayer;
			}
		}

	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx 0;
		box-sizing: border-box;
		width: 100%;
	}

	.ql-container {
		line-height: 160%;
		font-size: 34rpx;
		width: calc(100% - 60rpx);
		height: auto;
		margin: 0 auto;
		margin-top: 100px;
	}

	.tool-view {
		width: 100vw;
		position: absolute;
		top: 0;
		left: 0;
		margin-top: 150px;

	}

	.tool {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;
		width: 100%;
		background: #eee;
		margin-top: -65px;
	}

	.font-more {
		position: absolute;
		left: 0;
		bottom: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;
		width: 100%;
		background: rgb(235, 235, 235);
		overflow: hidden;
		transition: all 0.15s;
	}

	.setting-layer {
		position: absolute;
		bottom: 100rpx;
		background: #fff;
		width: 30%;
		right: 20rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		border-radius: 8rpx;
	}

	.setting-layer .single {
		height: 80rpx;
		font-size: 27rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		flex-direction: row;
		color: #666;
	}

	.setting-layer .single .icon {
		margin-right: 20rpx;
		color: #00BFFF;
	}

	.setting-layer-mask {
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background: transparent;
	}
</style>
